package com.yunxi.poc.starbucks.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunxi.poc.starbucks.common.BizConstant;
import com.yunxi.poc.starbucks.entity.Tb1TransactionSale;
import com.yunxi.poc.starbucks.mapper.Tb1TransactionSaleMapper;
import com.yunxi.poc.starbucks.service.ITb1TransactionSaleService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author shiyuan.xlc
 * @since 2021-08-09
 */
@Service
public class Tb1TransactionSaleServiceImpl extends ServiceImpl<Tb1TransactionSaleMapper, Tb1TransactionSale> implements ITb1TransactionSaleService {

    @Override
    public double calculateSales(List<Integer> storeIds, LocalDateTime startAt, LocalDateTime endAt) {

        double sales = 0D;

        // get transactions sales
        for (Integer storeId : storeIds) {
            QueryWrapper<Tb1TransactionSale> queryWrapperTrans = new QueryWrapper<>();
            queryWrapperTrans.eq("global_store_number", storeId);
            queryWrapperTrans.gt("sale_datetime", startAt);
            queryWrapperTrans.le("sale_datetime", endAt);
            // queryWrapperTrans.in("sale_item_code", CacheUtil.saleItemCodes);
            queryWrapperTrans.last("AND sale_item_code "
                    + "in ( SELECT distinct sale_item_code FROM saleitem_with_reportcategory "
                    + "where report_category in ("
                    + BizConstant.REPORT_CATEGORY.stream().map(e -> "'" + e + "'").collect(Collectors.joining(","))
                    + ") )");
            Double salesStore = this.getBaseMapper().sumSales(queryWrapperTrans);
            sales = Double.sum(Optional.ofNullable(salesStore).orElse(0D), sales);
        }

        return sales;
    }
}